package xyz.bali16.module.netdisk.utils;


import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class FtpUtil {
    /**
     * FTP服务器hostname
     */
    private static final String HOST = "127.0.0.1";
    /**
     * FTP服务器端口
     */
    private static final int PORT = 21;
    /**
     * FTP登录账号
     */
    private static final String USERNAME = "bali16";
    /**
     * FTP登录密码
     */
    private static final String PASSWORD = "bali16";
    /**
     * FTP服务器基础目录
     */
    private static final String BASEPATH = "";

    /**
     * 上传编码
     */
    private static final String uploadEncode = "iso-8859-1"; //iso-8859-1 ftpserver默认支持iso-8859-1

    /**
     * FTP客户端
     */
    private static FTPClient ftp;


    public static boolean initFtpClient() {
        ftp = new FTPClient();
        int reply;
        try {
            System.out.println(HOST);
            System.out.println(PORT);
            // 连接FTP服务器
            ftp.connect(HOST, PORT);
            //登录, 如果采用默认端口，可以使用ftp.connect(host)的方式直接连接FTP服务器
            ftp.login(USERNAME, PASSWORD);
            ftp.setBufferSize(10240);
            //设置传输超时时间为60秒
            ftp.setDataTimeout(600000);
            //连接超时为60秒
            ftp.setConnectTimeout(600000);
//            ftp.setControlEncoding("UTF-8");
            //FTP以二进制形式传输
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }

    public static boolean uploadFile(String filePath, String filename, InputStream input) {
        boolean result = false;
        try {
            filePath = new String(filePath.getBytes(StandardCharsets.UTF_8), uploadEncode);
            filename = new String(filename.getBytes(StandardCharsets.UTF_8), uploadEncode);
            System.out.println("filePath:" + filePath);
            System.out.println("filename:" + filename);
            if (!initFtpClient()) {
                return result;
            }
            //切换到上传目录
            ftp.enterLocalPassiveMode();
            if (!ftp.changeWorkingDirectory(BASEPATH + filePath)) {
                //如果目录不存在创建目录
                String[] dirs = filePath.split("/");
                String tempPath = BASEPATH;
                for (String dir : dirs) {
                    if (null == dir || "".equals(dir)) {
                        continue;
                    }
                    tempPath += "/" + dir;
                    if (!ftp.changeWorkingDirectory(tempPath)) {
                        if (!ftp.makeDirectory(tempPath)) {
                            return result;
                        } else {
                            ftp.changeWorkingDirectory(tempPath);
                        }
                    }
                }
            }
            //设置上传文件的类型为二进制类型
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            //上传文件
            ftp.enterLocalPassiveMode();
            if (!ftp.storeFile(filename, input)) {
                return result;
            }
            input.close();
            ftp.logout();
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }


    public static boolean downloadFile(String remotePath, String fileName, String localPath) {
        boolean result = false;

        try {
            remotePath = new String(remotePath.getBytes(StandardCharsets.UTF_8), uploadEncode);
            fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), uploadEncode);
            if (!initFtpClient()) {
                return result;
            }
            // 转移到FTP服务器目录
            ftp.changeWorkingDirectory(remotePath);
            ftp.enterLocalPassiveMode();
            FTPFile[] fs = ftp.listFiles();
            for (FTPFile ff : fs) {
                if (ff.getName().equals(fileName)) {
                    ftp.enterLocalPassiveMode();
                    FileOutputStream outputStream = new FileOutputStream(new File(localPath));
                    ftp.retrieveFile(remotePath + "/" + fileName, outputStream);

                    result = true;
                    outputStream.close();
                }
            }
            ftp.logout();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }


    public static boolean downloadFile(String remotePath, String fileName, OutputStream outputStream) {
        boolean result = false;
        try {
//            System.out.println(remotePath);
//            System.out.println(fileName);
//            System.out.println(remotePath.getBytes("UTF-8"));
//            System.out.println(fileName.getBytes("UTF-8"));
//            System.out.println(remotePath);
//            System.out.println(fileName);
            remotePath = new String(remotePath.getBytes(StandardCharsets.UTF_8), uploadEncode);
            fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), uploadEncode);
            if (!initFtpClient()) {
                outputStream.close();
                return result;
            }
            System.out.println("downloadFile!!:");
            System.out.println(remotePath);
            System.out.println(fileName);
            // 转移到FTP服务器目录
            ftp.changeWorkingDirectory(remotePath);
            ftp.enterLocalPassiveMode();
            FTPFile[] fs = ftp.listFiles();
            System.out.println("当前目录下的文件");

            for (FTPFile ff : fs) {
                System.out.println(ff.getName());
                if (ff.getName().equals(fileName)) {
                    ftp.enterLocalPassiveMode();
                    ftp.retrieveFile(remotePath + "/" + fileName, outputStream);
                    System.out.println("!!!");
                    System.out.println(remotePath + "/" + fileName);
                    result = true;
//                    outputStream.close();
                }
            }
            ftp.logout();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }

    public static boolean deleteFile(String remotePath, String fileName) {
        boolean flag = false;
        try {
            remotePath = new String(remotePath.getBytes(StandardCharsets.UTF_8), uploadEncode);
            fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), uploadEncode);
            if (!initFtpClient()) {
                return flag;
            }
            // 转移到FTP服务器目录
            ftp.changeWorkingDirectory(remotePath);
            ftp.enterLocalPassiveMode();
            FTPFile[] fs = ftp.listFiles();
            for (FTPFile ff : fs) {
                if ("".equals(fileName)) {
                    return flag;
                }
                if (ff.getName().equals(fileName)) {
                    String filePath = remotePath + "/" + fileName;
                    ftp.deleteFile(filePath);
                    flag = true;
                }
            }
            ftp.logout();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return flag;
    }


    public static boolean deleteFileFolder(String remotePath) {
        boolean flag = false;
        try {
            remotePath = new String(remotePath.getBytes(StandardCharsets.UTF_8), uploadEncode);
            if (!initFtpClient()) {
                return flag;
            }
            // 转移到FTP服务器目录
            ftp.changeWorkingDirectory(remotePath);
            ftp.enterLocalPassiveMode();
            FTPFile[] fs = ftp.listFiles();
            if (fs.length == 0) {
                ftp.removeDirectory(remotePath);
                flag = true;
            }
            ftp.logout();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return flag;
    }


    public static boolean reNameFile(String oldAllName, String newAllName) {
        boolean flag = false;
        try {
            oldAllName = new String(oldAllName.getBytes(StandardCharsets.UTF_8), uploadEncode);
            newAllName = new String(newAllName.getBytes(StandardCharsets.UTF_8), uploadEncode);
            if (!initFtpClient()) {
                return flag;
            }
            ftp.enterLocalPassiveMode();
            ftp.rename(oldAllName, newAllName);
            flag = true;
            ftp.logout();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return flag;
    }
}
